package com.kang.handler;

import com.kang.menu.PermissionMenu;
import com.kang.util.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * 3. 权限验证，是否放行
 */
@Slf4j
@Component
public class ScAuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext authorizationContext) {
        return authentication.map(auth -> {
            //此处根据请求路径判断是否有权限
            LoginUser scUser = (LoginUser) auth.getPrincipal();
            if (Objects.isNull(scUser)) {
                return new AuthorizationDecision(false);
            }
            if (scUser.getUser().getType() == 2) {
                return new AuthorizationDecision(true);
            } else {
                String path = authorizationContext.getExchange().getRequest().getPath().toString();
                String repPath = Pattern.compile("[\\d]").matcher(path).replaceAll("x");
                String perssionByPath = PermissionMenu.getPerssionByPath(repPath); //这是请求路径获取的权限
                List<String> userPermissions = scUser.getPermissions(); //权限集合
                if (perssionByPath != null && !userPermissions.contains(perssionByPath)) {
                    return new AuthorizationDecision(false);
                } else {
                    return new AuthorizationDecision(true);
                }
            }
        }).defaultIfEmpty(new AuthorizationDecision(false));

    }
}
